package thread.juc_usage;

import java.util.concurrent.Semaphore;

/**
 * @author yuisama
 * @date 2022/07/17 09:16
 * 信号量的使用
 **/
public class SemaphoreTest {
    public static void main(String[] args) {
        // 在构造参数传入可用资源的个数
        // 可用资源为6个
        Semaphore semaphore = new Semaphore(6);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "准备申请资源");
                    // P操作,每次申请两个资源
                    semaphore.acquire(2);
                    System.out.println(Thread.currentThread().getName() + "获取资源成功");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "释放资源");
                    // V操作，默认释放一个占有的资源
                    semaphore.release(2);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(runnable,String.valueOf(i + 1));
            t.start();
        }
    }
}